package com.five.filesync;

import android.os.AsyncTask;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class FileDownloaderRequest extends AsyncTask<String, Void, Boolean> {
    private static final String TAG = "FileDownloader";

    private static final boolean USE_CACHE = true;

    private String url;
    private File outputFile;
    private OnNetCallback callback;
    public FileDownloaderRequest(InetAddress host, int port, String dirname, File outputFile, OnNetCallback callback) {
        this.url = String.format("http://%s:%s/download/%s/%s", host.getHostAddress(), port, dirname, outputFile.getName());
        this.outputFile = outputFile;
        this.callback = callback;
    }

    @Override
    protected Boolean doInBackground(String... fileUrl) {

        OkHttpClient client = new OkHttpClient();

        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .build();

        // 发送请求
        try {
            Response response = client.newCall(request).execute();

            // 处理响应
            if (response.isSuccessful()) {
                // 获取响应体
                ResponseBody body = response.body();
                if (body != null) {
                    // 获取输入流
                    InputStream inputStream = body.byteStream();

                    // 创建保存文件的目录
                    File saveFile = outputFile;
                    File cacheFile = new File(outputFile.getAbsolutePath() + "_cache");
                    if (!saveFile.getParentFile().exists()) {
                        saveFile.getParentFile().mkdirs();
                    }
                    if (cacheFile.exists()) {
                        cacheFile.delete();
                    }

                    // 创建输出流
                    FileOutputStream fos = new FileOutputStream(USE_CACHE ? cacheFile : saveFile);

                    // 读取输入流并写入输出流
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        fos.write(buffer, 0, bytesRead);
                    }

                    // 关闭流
                    fos.flush();
                    fos.close();
                    inputStream.close();

                    if (USE_CACHE) {
                        Utils.copyFile(cacheFile, saveFile);
                    }

                    System.out.println("Download success. File saved at: " + saveFile.getAbsolutePath());
                    return true;
                } else {
                    extraInfo = "文件下载异常";
                    System.out.println("Download failed. Response body is null.");
                }
            } else {
                if (response.code() == 404) {
                    extraInfo = "文件不存在";
                } else {
                    extraInfo = "未知错误";
                }
                System.out.println("Download failed. Response code: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e(TAG, String.format("download %s failed", url));
        return false;
    }

    private String extraInfo;
    @Override
    protected void onPostExecute(Boolean ret) {
        if (this.callback != null) {
            this.callback.onResult(ret, extraInfo);
        }
    }
}